# Maintainer: Christian Rebischke <chris.rebischke@archlinux.org>
# Maintainer: George Rawlinson <grawlinson@archlinux.org>

pkgname=fluxcd
pkgver=2.1.2
pkgrel=1
pkgdesc='Open and extensible continuous delivery solution for Kubernetes'
arch=('loong64' 'x86_64')
url='https://fluxcd.io'
license=('Apache')
depends=('glibc')
makedepends=('git' 'go' 'kustomize')
replaces=('fluxctl')
options=('!lto')
_commit='a18d4f345021182d6516bf3e8e00210567f46ab5'
source=("$pkgname::git+https://github.com/fluxcd/flux2#commit=$_commit")
b2sums=('SKIP')

pkgver() {
  cd "$pkgname"

  git describe --tags | sed 's/^v//'
}

prepare() {
  cd "$pkgname"

  # create directory for build output
  mkdir build

  # download dependencies
  export GOPATH="${srcdir}"
  go mod download
}

build() {
  cd "$pkgname"

  # generate manifests
  # https://github.com/fluxcd/flux2/blob/c5b5263b1bd826e792b3e5607857b7cd6d981b62/.github/workflows/release.yaml#L55-L57
  make cmd/flux/.manifests.done
  ./manifests/scripts/bundle.sh "" ./output manifests.tar.gz
  kustomize build ./manifests/install > ./output/install.yaml

  # set Go flags
  export CGO_CPPFLAGS="${CPPFLAGS}"
  export CGO_CFLAGS="${CFLAGS}"
  export CGO_CXXFLAGS="${CXXFLAGS}"
  export GOPATH="${srcdir}"

  go build -v \
    -buildmode=pie \
    -mod=readonly \
    -modcacherw \
    -ldflags "-compressdwarf=false \
    -linkmode external \
    -extldflags ${LDFLAGS} \
    -X main.VERSION=${pkgver}" \
    -o build \
    ./cmd/...

  # generate shell completions
  cd build
  for shell in bash fish zsh; do
    ./flux completion "$shell" > "completion.$shell"
  done
}

check() {
  cd "$pkgname"

  go test -v ./...
}

package() {
  cd "$pkgname/build"

  # binary
  install -vDm755 -t "$pkgdir/usr/bin" flux

  # shell completions
  install -vDm644 completion.bash "$pkgdir/usr/share/bash-completion/completions/flux"
  install -vDm644 completion.fish "$pkgdir/usr/share/fish/vendor_completions.d/flux.fish"
  install -vDm644 completion.zsh "$pkgdir/usr/share/zsh/site-functions/_flux"
}
